package com.kchouse.union;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.model.LatLng;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.StartActivity;
import com.kchouse.bean.MerchantItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseFragment;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.SharedPreferencesUtil;
import com.kchouse.common.ToastUtils;
import com.kchouse.mine.LoginPhoneActivity;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.net.URISyntaxException;
import java.text.DecimalFormat;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

/**
 * A simple {@link Fragment} subclass.
 */
public class MerchantDetailsFragment extends BaseFragment implements View.OnClickListener {


    private JSONObject merchant;
    private View view;
    private LayoutInflater inflater;
    private TextView tv_name;
    private ImageView iv_icon;
    private TextView tv_mobile;
    private ImageView iv_vip;
    private TextView tv_addr;
    private View ll_navigation;
    public static final String PACKEGE_GAODE = "com.autonavi.minimap";
    public static final String PACKEGE_BAIDU = "com.baidu.BaiduMap";
    private String latitude;
    private String longitude;
    private TextView tv_detail;
    private View ll_focus;
    private boolean isLogin = false;
    private Intent intent = new Intent();
    private ImageView iv_focus;
    private boolean isfocus = false;//是否关注
    private String merchantName;

    public MerchantDetailsFragment() {
    }

    @SuppressLint("ValidFragment")
    public MerchantDetailsFragment(JSONObject merchant) {

        this.merchant = merchant;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (view == null) {
            this.inflater = inflater;
            view = inflater.inflate(R.layout.fragment_merchant_details, null);
            intiData();
            intiView();

        }
        return view;
    }

    private void intiView() {

        tv_name = (TextView) view.findViewById(R.id.tv_name);
        String name = merchant.getString("name");
        tv_name.setText(name);
        iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
        iv_icon.setOnClickListener(this);
        String url = merchant.getString("url");
        Picasso.with(getActivity()).load(url).error(R.mipmap.ic_loadingerror).into(iv_icon);
        tv_mobile = (TextView) view.findViewById(R.id.tv_mobile);
        String contactMobile = merchant.getString("contactMobile");
        tv_mobile.setText("电话：" + contactMobile);
        iv_vip = (ImageView) view.findViewById(R.id.iv_vip);
        int vipStatus = merchant.getInteger("vipStatus");
        if (vipStatus == 1) {
            iv_vip.setVisibility(View.VISIBLE);
        } else {
            iv_vip.setVisibility(View.GONE);
        }
        tv_addr = (TextView) view.findViewById(R.id.tv_addr);
        latitude = merchant.getString("latitude");
        longitude = merchant.getString("longitude");
        merchantName = merchant.getString("name");
        intiDistance(tv_addr, latitude, longitude);
        ll_navigation = view.findViewById(R.id.ll_navigation);
        ll_navigation.setOnClickListener(this);
        ll_focus = view.findViewById(R.id.ll_focus);
        ll_focus.setOnClickListener(this);
        iv_focus = (ImageView) view.findViewById(R.id.iv_focus);
        tv_detail = (TextView) view.findViewById(R.id.tv_detail);
        String details = merchant.getString("details");
        tv_detail.setText(details);
    }


    /**
     * 距离计算
     *
     * @param
     * @param
     */
    private void intiDistance(TextView tv, String Latitude, String Longitude) {
        LatLng startLatlng = new LatLng(StartActivity.mLatitude, StartActivity.mLongitude);
        LatLng endLatlng = new LatLng(Double.valueOf(Latitude), Double.valueOf(Longitude));

        double distance = AMapUtils.calculateLineDistance(startLatlng, endLatlng);
        distance = distance / 1000;
        DecimalFormat df = new DecimalFormat("0.##");
        String st = df.format(distance);
        tv.setText(st + "km");
    }

    private void intiData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_navigation:
                navigation("厦门", merchantName, latitude, longitude);
                break;
            case R.id.iv_icon:
                String url = merchant.getString("url");
                intent.putExtra("url",url);
                intent.setClass(getActivity(),PhotoActivity.class);
                startActivity(intent);

                break;
            case R.id.ll_focus:
                if (checkLogin()) return;
                if (isfocus) {
                    DelFocus();
                } else {
                    PostAddFocus();
                }
                break;
        }
    }

    /**
     * 取消关注
     */
    private void DelFocus() {
        String url = API.DelFocus + MainActivity.userid + "/" + merchant.getString("id");
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addFormDataPart("userId", MainActivity.userid);
        params.addFormDataPart("merchantId", merchant.getString("id"));
        params.addHeader("token", MainActivity.token);//添加header信息
        HttpRequest.delete(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    iv_focus.setImageResource(R.mipmap.ic_focus_off);
                    isfocus = false;
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(getActivity()).showToast(data.getString("msg"));
                    if (data.getString("code").equals("401")) {
                        intent.setClass(getActivity(), LoginPhoneActivity.class);
                        startActivity(intent);
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    /**
     * 添加关注
     */
    private void PostAddFocus() {
        String url = API.PostAddFocus;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        JSONObject ob = new JSONObject();
        ob.put("userId", MainActivity.userid);
        ob.put("merchantId", merchant.getString("id"));
        params.addHeader("token", MainActivity.token);//添加header信息
        params.applicationJson(ob);


        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    iv_focus.setImageResource(R.mipmap.ic_focus_on);
                    isfocus = true;
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(getActivity()).showToast(data.getString("msg"));
                    if (data.getString("code").equals("401")) {
                        intent.setClass(getActivity(), LoginPhoneActivity.class);
                        startActivity(intent);
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    /**
     * 校验登录状态
     *
     * @return
     */
    private boolean checkLogin() {
        // 如果未登录都进入登录界面
        if (!isLogin) {
            intent.setClass(getActivity(), LoginPhoneActivity.class);
            startActivity(intent);
            return true;
        }
        return false;
    }

    @Override
    public void onResume() {
        super.onResume();

        if (!MainActivity.mobile.equals("")) {
            isLogin = true;

            GetCheckFocus();
        } else {
            isLogin = false;
        }
    }

    /**
     * 校验是否关注
     */
    private void GetCheckFocus() {
        String url = API.GetCheckFocus + MainActivity.userid + "/" + merchant.getString("id");
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addFormDataPart("userId", MainActivity.userid);
        params.addFormDataPart("merchantId", merchant.getString("id"));
        params.addHeader("token", MainActivity.token);//添加header信息

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    isfocus = json.getBooleanValue("data");
                    if (isfocus) {
                        iv_focus.setImageResource(R.mipmap.ic_focus_on);
                    } else {
                        iv_focus.setImageResource(R.mipmap.ic_focus_off);
                    }

                } else {
                    String datastr = json.getString("data");
//                    JSONObject data = JSONObject.parseObject(datastr);
//                    ToastUtils.getInstanc(getActivity()).showToast(data.getString("msg"));
//                    if (data.getString("code").equals("401")) {
//                        intent.setClass(getActivity(), LoginPhoneActivity.class);
//                        startActivity(intent);
//                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });

    }


    /**
     * 城市名 位置名  目的地纬度 目的地经度(跳转到地图软件进行导航,优先选用高德地图,其次用百度地图)
     */
    private void navigation(String city, String position, String lat, String lon) {
        try {
            Intent intent = null;
            if (isInstallByread(PACKEGE_GAODE)) {
                //高德地图导航的代码
//                Toast.makeText(context, "打开高德地图", Toast.LENGTH_SHORT).show();
                intent = Intent.parseUri("androidamap://viewMap?sourceApplication=appname&poiname=" + position + "&lat=" + lat + "&lon=" + lon + "&dev=0", 0);
            } else if (isInstallByread(PACKEGE_BAIDU)) {
                //百度地图导航的代码
//                Toast.makeText(context, "打开百度地图", Toast.LENGTH_SHORT).show();
                intent = Intent.parseUri("intent://map/geocoder?location=" + lat + "," + lon + "&coord_type=gcj02&src=yourCompanyName|yourAppName#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end", 0);
            } else {
//                ToastUtils.getInstanc(context).showToast("未安装高德或者百度地图软件");
            }
            if (intent != null) {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getActivity().startActivity(intent);
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断是否安装目标应用
     *
     * @param packageName 目标应用安装后的包名
     * @return 是否已安装目标应用
     */
    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }

}
